var config = require('../../config');
var common = require('../utils/common.js');
var loadRecord = require('loadRecord.js');
var loadRequest = require('../index/loadRequest.js');
var app = getApp();
var username = '';//用户登录id
var page = 0;
var size = 8;//视频分页
var ssize = 12;//系列分页
var tab_page = {};

var menu_page = [];//tab切换
var materials_page = {};//视频记录
var series_page = {};//系列记录
var index = 0;//默认索引

var touchDot = 0;//触摸时的原点
var time = 0;//  时间记录，用于滑动时且时间小于1s则执行左右滑动
var interval = "";// 记录/清理 时间记录
var tmpFlag = true;// 判断左右华东超出菜单最大值时不再执行滑动事件
Page({

  /**
   * 页面的初始数据
   */
  data: {
    series_list: [],
    material_list: [],
    lastLoadTime: 0,
    windowHeight: 0,
    menu_list: [],
    index: 0,
    items: [],
    startX: 0, //开始坐标
    startY: 0,
    clickId:0,
    editable:true,//是否编辑默认为true
    allcheck:false,//0表示未选择，1表示选择
    items: [
      { value: 'USA', name: '美国' },
      { value: 'CHN', name: '中国', checked: 'true' },
      { value: 'BRA', name: '巴西' },
      { value: 'JPN', name: '日本' },
      { value: 'ENG', name: '英国' },
      { value: 'FRA', name: '法国' },
    ],
    delstr:'删除',
    num:0,
    showf:false,
  },
  radioChange: function (e) {

    var items = this.data.items;
    for (var i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value == e.detail.value
    }

    this.setData({
      items: items
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中···',
    });
    series_page = {};
    materials_page = {};
    app.getUserName(function (user_name) {
      console.log('我是user_name::' + user_name);
      username = user_name;
      var data = {
        page: page,
        size: size
      };
      
      loadRecord.load_material_page(data, materials_page, username, that);
      var data = {
        page: page,
        size: ssize
      };
      //loadRecord.load_series_page(data, series_page, username, that);

    });

    wx.getSystemInfo({
      success: function (res) {
        //赋值
        that.setData({
          windowHeight: res.windowHeight - 30
        });
      }
    });
    menu_page = []
    var menu = {};
    // menu.name = "视频记录";
    menu.name = "播放记录";
    menu.class_name = "active";

    menu_page.push(menu);

    //  menu = {};
    //  menu.name = "系列记录";
    //  menu.name = "";
    //  menu_page.push(menu);

    that.setData({
      menu_list: menu_page
    });
  },

  

  //长按删除系列
  delSeries:function(e){
    var that=this;
    var id=e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '您确定要删除该系列记录?',
      success: function (res) {
        if (res.confirm) {
          //执行删除系列的请求
            // wx.request({
            //   url: ,
            // })
          var series_list=series_page.series_list;
          var list=new Array();
          for(var i=0;i<series_list.length;i++){
            if(series_list[i].id!=id){
              list.push(series_list[i]);
            }
          }
          series_page.series_list=list;
          that.setData({
            series_list:list
          });
        }
      }
    });  

},//删除事件
  del: function (e) {//单个删除
   var index=e.currentTarget.dataset.index ;
   var id= e.currentTarget.dataset.id;
   var that=this;
   wx.showModal({
     title:'提示',
     content:'您确定要删除该条记录?',
     success: function (res) {
       if (res.confirm) {
         var material_list=materials_page.material_list;
         var materials=new Array();
         for(var i=0;i<material_list.length;i++){
            if(i!=index){
              materials.push(material_list[i]);
            }
         }
         //materials_page.material_list = material_list.splice(index, 1)
         materials_page.material_list = materials;
         that.setData({
           material_list: materials_page.material_list
         });
          //删除播放的记录信息
         app.getNUserName(function (username) {
           if (username) {
              wx.request({
                url: config.materials +'/hide-view',
                data:{
                  materialIds:id,
                  username:username
                },
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                }
              });
           }
         });
         this.checkCheckbox();
       }
     } 
    });
  },
  exec_del: function (username, id) {//根据id删除
    wx.request({
      url: config.materials + '/hide-view',
      data: {
        materialIds: id,
        username: username
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
      }
    });
  },
  //删除多个记录
  delMulti:function(e){
    var that=this;
    var ids="";
    var material_list = materials_page.material_list;
    for (var i = 0; i < material_list.length; i++) {
      if (material_list[i].checked) {
        ids += material_list[i].id+',';
      }
    }
    if(ids==""){//
      wx.showModal({
        title: '提示',
        content: '请选择要删除的数据?',
        success:function(res){
        }
      });  
      return;
    }
    wx.showModal({
      title: '提示',
      content: '您确定要删除已选择的播放记录数据?',
      success: function (res) {
        if(res.confirm){
          var materials = new Array();
          for (var i = 0; i < material_list.length; i++) {
            if (!material_list[i].checked) {
              materials.push(material_list[i]);
            }
          }
          materials_page.material_list = materials;
          that.setData({
            material_list: materials
          });

          ids = ids.substring(0, ids.length - 1);
          //删除播放的记录信息
          app.getNUserName(function (username) {
            if (username) {
              for (var i = 0; i < material_list.length; i++) {
                if (material_list[i].checked) {
                  that.exec_del(username, material_list[i].id);
                }
              }

              // wx.request({
              //   url: config.materials + '/hide-view',
              //   data: {
              //     materialIds: ids,
              //     username: username
              //   },
              //   header: {
              //     'content-type': 'application/json'
              //   },
              //   success: function (res) {
              //   }
              // });
            }
          });
          that.checkCheckbox();
        }
      }
    });  
   
    
  },
  checkboxChange:function(e){
    var index = e.currentTarget.dataset.index;//e.detail.value;
    var checked=e.currentTarget.dataset.checked;
    console.log(index+'::'+checked);
    var material_list = materials_page.material_list;
    for (var i = 0; i < material_list.length; i++) {
      if (index==i){
        material_list[i].checked = !checked;
        break;
      }
    }
    tab_page.material_list = material_list;
    this.setData({
      material_list: tab_page.material_list
    });
    this.checkCheckbox();
  },checkCheckbox:function(){//验证是否都全选了
    var material_list = materials_page.material_list;
    var flag=true;//表示全选
    var num=0;
    for (var i = 0; i < material_list.length; i++) {
      if (!material_list[i].checked){
          flag=false;
          //break;
      }else{
        num++;
      }   
    }
    this.setData({
      allcheck: flag,
      delstr: num>0? '删除(' + num + ')':'删除' ,
      num:num
    });

  },
  allChange:function(e){//全选
    var checked=e.currentTarget.dataset.checked;
    this.setData({
      allcheck:!checked
    });
    var material_list=materials_page.material_list;
    for (var i = 0; i < material_list.length;i++){
      material_list[i].checked=!checked;
    }
    tab_page.material_list = material_list;
    this.setData({
      material_list: tab_page.material_list
    });
    this.checkCheckbox();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面

    prevPage.setData({
      historyId: 0
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    // return {
    //   title: config.shareName,
    //   desc: config.shareDes,//
    // }
    return {
      title: config.shareDes,
      path: '/pages/index/index',
      imageUrl: '../images/sharepic_1.jpg'
    }

  }, inplay_series: function (e) {//进入系列
    var id = e.currentTarget.dataset.id;
    if (id == 0 || id == null) {
      return;
    }
    if (this.data.clickSeriesId == id) {
      return;
    }
    this.setData({
      clickSeriesId: id
    });
    wx.navigateTo({
      url: '../search/seriesList/serieslist?id=' + id
    })
  }, inplay_material_p: function (e) {//进入播放页面 父页面
    var title = e.currentTarget.dataset.title;
    var id = e.currentTarget.dataset.id;
    if (id == 0 || id == null) {
      return;
    }
    if (this.data.clickId == id) {
      return;
    }
    this.setData({
      clickId: id
    });
    var url = '../video/video?id=' + id + '&title=' + title;
    wx.navigateTo({
      url: url
    })

  }, favor: function (e) {//收藏
    var that = this;
    var idd = e.currentTarget.dataset.id;
    var fid = e.currentTarget.dataset.fid;//是否收藏1 是，0 否

    if (idd == 0 || idd == null) {
      return;
    }
    app.getUserName(function (username) {
      if (fid == '1') {//表示取消收藏   
        common.add_rem_favorite(idd, username, 'remove',
          function () {
            var list = that.data.material_list;
            for (var i = 0; i < list.length; i++) {
              if (list[i].id == idd) {
                list[i].favorite = '0';
              }
            }
            that.setData({
              material_list: list
            });

          });
      }
      else {//表示需要收藏
        common.add_rem_favorite(idd, username, 'add', function () {
          var list = that.data.material_list;
          for (var i = 0; i < list.length; i++) {
            if (list[i].id == idd) {
              list[i].favorite = '1';
            }
          }
          that.setData({
            material_list: list
          });
        });
      }
    });
  }, tabEvent: function (e) {//切换
    var that = this;
    index = e.currentTarget.dataset.index;

    for (var i = 0; i < menu_page.length; i++) {
      if (index == i) {
        menu_page[i].class_name = "active";
      } else {
        menu_page[i].class_name = "";
      }
    };
   
    that.setData({
      menu_list: menu_page,
      index: index
    });

  }, loadMore: function (e) {//加载更多
    var that = this;
    if (index == 0) {

      var currentPage = materials_page.page + 1;
      if (currentPage < materials_page.pageSize) {
        var curTime = new Date().getTime();
        //上一次加载的时间
        var lastTime = this.data.lastLoadTime;
        that.setData({
          lastLoadTime: curTime
        });
        if (curTime - lastTime < 300) {
          return;
        }

        wx.showLoading({
          title: '加载中···',
        });
        var data = {
          page: currentPage,
          size: size
        };

        loadRecord.load_material_page(data, materials_page, username, that);

      }
    } else {
      var currentPage = series_page.page + 1;
      if (currentPage < series_page.pageSize) {
        var curTime = new Date().getTime();
        //上一次加载的时间
        var lastTime = this.data.lastLoadTime;
        that.setData({
          lastLoadTime: curTime
        });
        if (curTime - lastTime < 300) {
          return;
        }
        wx.showLoading({
          title: '加载中···',
        });
        var data = {
          page: currentPage,
          size: ssize
        };

        loadRecord.load_series_page(data, series_page, username, that);
      }

    }
    var timeout = setTimeout(function () {
      wx.hideLoading();
      clearTimeout(timeout);
    }, 500);
  }, refesh: function (e) {
  },
  // 触摸开始事件
  touchStart: function (e) {
    touchDot = e.touches[0].pageX; // 获取触摸时的原点
    // 使用js计时器记录时间    
    interval = setInterval(function () {
      time++;
    }, 100);
  },
  // 触摸移动事件
  // touchMove: function (e) {
  //   var touchMove = e.touches[0].pageX;
  //   // 向左滑动   
  //   if (touchMove - touchDot <= -40) {
  //     if (tmpFlag) { //每次移动中且滑动时不超过最大值 只执行一次 ++
  //       tmpFlag = false;
  //       index = index == 1 ? 1 : index + 1;
  //       this.slip(index);
  //     }
  //   }

  //   // 向右滑动
  //   if (touchMove - touchDot >= 40) {
  //     if (tmpFlag) {
  //       tmpFlag = false;
  //       index = index == 0 ? 0 : index - 1;
  //       this.slip(index);
  //     }
  //   }
  // },
  // 触摸结束事件
  // touchEnd: function (e) {
  //   clearInterval(interval); // 清除setInterval
  //   time = 0;
  //   tmpFlag = true; // 回复滑动事件
  // },
  slip: function (index) {
    var that = this;

    for (var i = 0; i < menu_page.length; i++) {
      if (index == i) {
        menu_page[i].class_name = "active";
      } else {
        menu_page[i].class_name = "";
      }
    };
    that.setData({
      menu_list: menu_page,
      index: index
    });
  },edit:function(e){//编辑
    this.setData({
      editable: false
    });
  },cancel:function(e){//取消
      this.setData({
        editable:true
      });
  }

})